import json

from django.http import HttpResponse, JsonResponse, HttpRequest
from django.contrib.auth import authenticate, login

from user_center.const import MetaOk
from django.views.decorators.csrf import csrf_exempt


def ping(request):
    return HttpResponse("pong")


@csrf_exempt
def login_(request: HttpRequest):
    data = json.loads(request.body)
    username = data['username']
    password = data['password']
    user = authenticate(username=username, password=password)
    if not user:
        login_fail = {
            "meta": {
                "code": 20019,
                "msg": "用户名或密码错误"
            }
        }
        return JsonResponse(login_fail)
    login(request, user)
    login_success = {
        "meta": MetaOk
    }
    return JsonResponse(login_success)
